import { FunctionEvent, fromEvent } from 'graphcool-lib'

type User = {
  id: string
  password: string
}

type Event = FunctionEvent<{
  username: string
  password: string
}>

export default async (event: Event) => {
  try {
    const { data } = event
    const graphcool = fromEvent(event)
    const api = graphcool.api('simple/v1')

    const query = `
      query ($username: String!) {
        User(username: $username) {
          id
          password
        }
      }
    `

    type R = { User: User }

    const { User: user } = await api.request<R>(query, data)

    if (!user || !checkPassword(data, user)) {
      return { error: 'invalid credentials' }
    }

    const token = await graphcool.generateNodeToken(user.id, 'User')

    return { data: { token, userId: user.id } }
  } catch (error) {
    return { error }
  }
}

const checkPassword = (
  input: { password: string },
  user: { password: string },
) => input.password === user.password
